﻿/*文件注释
 * ===============================================================================
 * 说明：
 * 作者：曾永佑
 * 版本：V1.0
 * 创建日期：2013-02-28
 * 完成日期： 
 * 修改纪录：  
 * ===============================================================================
 */  
        
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Web; 
using System.Web.Mvc;
using System.Reflection;
using System.ComponentModel.DataAnnotations;
using System;

namespace SRF.UI.Html
{
    public static class AuthorizeExtensions
    {
        #region Authorize

        /// <summary>
        /// html标签授权
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="actionItems"></param>
        /// <returns></returns>
        public static MvcHtmlString Authorize(this HtmlHelper htmlHelper, params ActionItem[] actionItems)
        {
            // 获取没有授权的元素 
            var denyList = from a in actionItems
                           where !SRF.Security.SecurityContext.HasActionGrant(a.Action)
                           select new
                           {
                               Element = a.Element,
                               Attribute = a.Attribute
                           };
            var json = (new System.Web.Script.Serialization.JavaScriptSerializer()).Serialize(denyList);

            StringBuilder scriptBuilder = new StringBuilder();
            scriptBuilder.AppendLine("<script type='text/javascript' language='javascript'>");
            scriptBuilder.AppendLine("$(function(){");
            scriptBuilder.AppendLine("var actions=" + json + ";");
            scriptBuilder.AppendLine("security.verify(actions);");
            scriptBuilder.AppendLine("})");
            scriptBuilder.AppendLine("</script>");

            return new MvcHtmlString(scriptBuilder.ToString());
        }

        #endregion
    }

    public class ActionItem
    {
        public ActionItem(string element, string attribute, string action)
        {
            Element = element;
            Attribute = attribute;
            Action = action;
        }

        public string Element { get; set; }
        public string Attribute { get; set; }
        public string Action { get; set; }
    }
}